$(function() {
	var $situationDate = $('#situationDate');
	var $hiddenLatestDay = $('#hiddenLatestDay');
	var $dataTable = $('#dataTable');
	var $btnRefresh = $('#btnRefresh');
	var $btnExport = $('#btnExport');
	var $btnOptionToggle = $('#btnOptionToggle');
	var $optionDialog = $('#optionDialog');
	var $optionTable = $('#optionTable');
	var $optionEditDialog = $('#optionEditDialog');
	var $optionEditDialogLabel = $('#optionEditDialogLabel');
	
	var $optionEditForm = $('#optionEditForm');
	var $effectiveDate = $('#effectiveDate');
	var $electricityPrice = $('#electricityPrice');
	var $optionNumMinerTable = $('#optionNumMinerTable');
	var $btnResetOption = $('#btnResetOption');
	var $btnSaveOption = $('#btnSaveOption');
	
	var minerTypes; // 矿机类型列表
	var currentOption; // 当前编辑的配置
	
	initWidgets();
	initListeners();
	initValidators();
	
	function openOptionEditDialog(option) {
		if (!option) {
			return;
		}
		currentOption = option;
		
		$optionEditDialogLabel.text('矿场运营配置 : ' + option.effectiveDate);
		
		initFormData(option);
		
		$optionEditDialog.modal('show');
	}
	
	function initFormData(option) {
		$effectiveDate.text(option.effectiveDate);
		$electricityPrice.val(option.electricityPrice);
		
		var numOfTypes = [];
		var numManaged = option.numManagedOfTypes;
		var numInvalid = option.numInvalidOfTypes;
		var electricity = option.electricityOfTypes;
		if (numManaged) {
			$.each(numManaged, function (key, value) {
				var numOfType = {};
				numOfType.name = key;
				numOfType.numManaged = value;
				numOfType.numInvalid = 0;
				numOfType.electricity = 0;
				numOfTypes.push(numOfType);
			});
		}
		if (numInvalid) {
			$.each(numInvalid, function (key, value) {
				var numOfType = null;
				for (var i=0; i<numOfTypes.length; i++) {
					if (key == numOfTypes[i].name) {
						numOfType = numOfTypes[i];
						break;
					}
				}
				if (numOfType) {
					numOfType.numInvalid = value;
				} else {
					var numOfType = {};
					numOfType.name = key;
					numOfType.numManaged = 0;
					numOfType.numInvalid = value;
					numOfType.electricity = 0;
					numOfTypes.push(numOfType);
				}
			});
		}
		if (electricity) {
			$.each(electricity, function (key, value) {
				var numOfType = null;
				for (var i=0; i<numOfTypes.length; i++) {
					if (key == numOfTypes[i].name) {
						numOfType = numOfTypes[i];
						break;
					}
				}
				if (numOfType) {
					numOfType.electricity = value;
				} else {
					var numOfType = {};
					numOfType.name = key;
					numOfType.numManaged = 0;
					numOfType.numInvalid = 0;
					numOfType.electricity = value;
					numOfTypes.push(numOfType);
				}
			});
		}
		if (minerTypes && minerTypes.length > 0) {
			for (var i=0; i<minerTypes.length; i++) {
				var minerType = minerTypes[i];
				var numOfType = null;
				for (var j=0; j<numOfTypes.length; j++) {
					if (minerType.name == numOfTypes[j].name) {
						numOfType = numOfTypes[j];
						break;
					}
				}
				if (!numOfType) {
					numOfType = {};
					numOfType.name = minerType.name;
					numOfType.numManaged = 0;
					numOfType.numInvalid = 0;
					numOfType.electricity = 0;
					numOfTypes.push(numOfType);
				}
			}
		}
		$optionNumMinerTable.bootstrapTable('load', numOfTypes);
	}
	
	function saveOption() {
		var valid = $optionEditForm.validate().form();
		if (!valid) {
			return;
		}
		
		var numOfTypes = $optionNumMinerTable.bootstrapTable('getData');
		var numManageds = {};
		var numInvalids = {};
		var electricitys = {};
		if (numOfTypes) {
			for (var i=0; i<numOfTypes.length; i++) {
				var numOfType = numOfTypes[i];
				if ($.isNumeric(numOfType.numManaged)) {
					var numManaged = parseInt(numOfType.numManaged);
					if (numManaged > 0) {
						numManageds[numOfType.name] = numManaged;
					}
				}
				if ($.isNumeric(numOfType.numInvalid)) {
					var numInvalid = parseInt(numOfType.numInvalid);
					if (numInvalid > 0) {
						numInvalids[numOfType.name] = numInvalid;
					}
				}
				if ($.isNumeric(numOfType.electricity)) {
					var electricity = parseFloat(numOfType.electricity);
					if (electricity > 0) {
						electricitys[numOfType.name] = electricity;
					}
				}
			}
		}
		var electricityPrice = $electricityPrice.val();
		if ($.isNumeric(electricityPrice)) {
			electricityPrice = parseFloat(electricityPrice);
		}
		currentOption.electricityPrice = electricityPrice;
		currentOption.numManagedOfTypes = numManageds;
		currentOption.numManagedOfTypesJson = JSON.stringify(numManageds);
		currentOption.numInvalidOfTypes = numInvalids;
		currentOption.numInvalidOfTypesJson = JSON.stringify(numInvalids);
		currentOption.electricityOfTypes = electricitys;
		currentOption.electricityOfTypesJson = JSON.stringify(electricitys);
		doSaveOption(currentOption);
	}
	
	function doSaveOption(option) {
		$.ajax({
			url: 'situations/option',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: JSON.stringify(option),
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '保存成功');
					$optionTable.bootstrapTable('refresh');
					$optionEditDialog.modal('hide');
				} else {
					toastr.error(result.message, '保存失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}
	
	function openOptionDialog() {
		$.ajax({
			url: 'types',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					minerTypes = result.data; // 矿机类型列表
					$optionTable.bootstrapTable('refresh');
					$optionDialog.modal('show');
				} else {
					toastr.error('矿机类型列表获取失败', '错误');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}
	
	function restats(option) {
		// TODO K 验证锁定、权限等
		var latestDay = $hiddenLatestDay.val();
		if (option.effectiveDate > latestDay) {
			toastr.warning('该日数据尚未收集完成，无法统计！', '提示');
			return;
		}
		swal({
			html: true,
	        title: '将重新统计 ' + option.effectiveDate + ' 的矿场运营情况。',
	        text: '旧的统计结果将被覆盖，请谨慎操作。',
	        type: "warning",
	        showCancelButton: true,
	        cancelButtonText : "让我再考虑一下…",
	        confirmButtonColor: "#ed5565",
	        confirmButtonText : "是的，我要执行！"
	    }, function(isConfirm) {
			if (isConfirm) {
				doRestats(option);
			}
		});
	}
	
	function doRestats(option) {
		loadmask.show('正在执行统计，请稍后...');
		$.ajax({
			url: 'situations/restats',
			type: 'POST',
			dataType: 'json',
			data: {
				effectiveTime: option.effectiveTime
			},
			success: function(result) {
				if (result.success) {
					toastr.success('重新统计成功！', '成功');
					$optionTable.bootstrapTable('refresh');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '失败');
				}
				loadmask.hide();
			},
			error: function(request, status, error) {
				loadmask.hide();
				toastr.error(error, '异常');
			}
		});
	}
	
	function getHeight() {
	    return $(window).height() - $('#topInfo').outerHeight() - 60;
	}
	
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$optionEditForm.validate({
			rules: {
				electricityPrice: { required: false, number: true, min: 0 },
				electricityQuantity: { required: false, number: true, min: 0 }
			},
			messages: {
				electricityPrice: validIcon + '无效的电价。',
				electricityQuantity: validIcon + '无效的电量。'
			}
		});
	}
	
	function initListeners() {
		$(window).resize(function () {
			$dataTable.bootstrapTable('resetView', {
	            height: getHeight()
	        });
	    });
		
		$situationDate.on('changeDate', function() {
			var date = $situationDate.datepicker('getDate');
			var isDate = Object.prototype.toString.call(date) === "[object Date]";
			isDate &= !isNaN(date.getTime());
			if (!isDate) {
				var latestDay = $hiddenLatestDay.val();
				$situationDate.datepicker('update', latestDay);
			}
			$dataTable.bootstrapTable('refresh');
		});
		
		$btnRefresh.on('click', function() {
			$dataTable.bootstrapTable('refresh');
		});
		
		$btnOptionToggle.on('click', function() {
			openOptionDialog();
		});
		
		$btnResetOption.on('click', function() {
			initFormData(currentOption);
		});
		
		$btnSaveOption.on('click', function() {
			saveOption();
		});
		
		$btnResetOption.on('click', function() {
			initFormData(currentOption);
		});
		
		$btnExport.on('click', function() {
			var date = $situationDate.datepicker('getDate');
			var isDate = Object.prototype.toString.call(date) === "[object Date]";
			isDate &= !isNaN(date.getTime());
			if (isDate) {
				var latestDay = $hiddenLatestDay.val();
				var latestTime = new Date(latestDay).getTime();
				if (date.getTime() <= latestTime) {
					date = date.format('yyyy-MM-dd');
					$('#downloadFrame').prop('src', 'situations/export/' + date);
				} else {
					toastr.warning('所选日期尚无数据！', '导出失败');
				}
			} else {
				toastr.warning('请选择正确的日期！', '提示');
			}
		});
	}
	
	function initWidgets() {
		var latestDay = $hiddenLatestDay.val();
		$situationDate.datepicker({
		    format: 'yyyy-mm-dd',
		    endDate: latestDay,
		    language: 'zh-CN',
		    autoclose: true
		});
		$situationDate.datepicker('update', latestDay);
		
		initSituationTable();
		initOptionTable();
		initOptionNumMinerTable();
	}
	
	function initSituationTable() {
		// 表格
		$dataTable.bootstrapTable({
			height: getHeight(),
			url: 'situations',
			idField: 'id',
			showToggle: true,
			showColumns: true,
			showRefresh: true,
			toolbar: '#dataTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			queryParams: function(params) {
				var date = $situationDate.datepicker('getDate');
				var isDate = Object.prototype.toString.call(date) === "[object Date]";
				isDate &= !isNaN(date.getTime());
				if (isDate) {
					date = date.format('yyyy-MM-dd');
					return { date: date };
				} else {
					return {};
				}
			},
			columns: [
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					valign: 'middle',
					visible: false
				},
				{
					field: 'minerTypeId',
					title: '矿机类型ID',
					align: 'center',
					valign: 'middle',
					visible: false
				},
				{
					field: 'minerTypeName',
					title: '矿机类型',
					halign: 'center',
					align: 'left',
					valign: 'middle'
				},
				{
					field: 'numManaged',
					title: '托管数',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return toThousands(value);
					}
				},
				{
					field: 'numInvalid',
					title: '失效数',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return toThousands(value);
					}
				},
				{
					field: 'rateInvalid',
					title: '失效比',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				},
				{
					field: 'numLT80',
					title: '不合格数<br>(算力低于80%)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return toThousands(value);
					}
				},
				{
					field: 'ratePassed',
					title: '合格率',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				},
				{
					field: 'overallTheory',
					title: '理论算力(P)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney((value / 1000 / 1000), 4);
					}
				},
				{
					field: 'passedTheory',
					title: '合格矿机<br>理论算力(P)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney((value / 1000 / 1000), 4);
					}
				},
				{
					field: 'passedAverage24',
					title: '合格矿机<br>24小时<br>平均算力(P)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney((value / 1000 / 1000), 4);
					}
				},
				{
					field: 'diffRatePassedAverage24',
					title: '合格矿机<br>24小时<br>平均算力差异',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				},
				{
					field: 'pool',
					title: '矿池总算力(P)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney((value / 1000 / 1000), 4);
					}
				},
				{
					field: 'diffRatePool',
					title: '矿池总算力差异',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				},
				{
					field: 'chargeGT80',
					title: '监控电费<br>(算力>80%)',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney(value, 2);
					}
				},
				{
					field: 'chargeReal',
					title: '矿场实际电费',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney(value, 2);
					}
				},
				{
					field: 'diffRateChargeGT80',
					title: '80%算力以上<br>电费差异',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				},
				{
					field: 'chargePool',
					title: '矿池电费',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return formatMoney(value, 2);
					}
				},
				{
					field: 'diffRateChargePool',
					title: '矿池电费差异',
					halign: 'center',
					align: 'right',
					valign: 'middle',
					formatter: function(value, row, index) {
						return (formatMoney(value * 100, 2)) + '%';
					}
				}
			]
		});
	}
	
	function initOptionTable() {
		$optionTable.bootstrapTable({
			height: 400,
			url: 'situations/option',
			idField: 'id',
			showToggle: true,
			showColumns: true,
			showRefresh: true,
			pagination: true,
			sidePagination: 'server',
			pageList: [10, 25, 50, 100],
			toolbar: '#optionTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			rowStyle: function(row, index) {
				var latestDay = $hiddenLatestDay.val();
				var timeZoneID = $('#hiddenTimeZoneID').val();
				var date = moment.tz(row.effectiveTime, timeZoneID).format('YYYY-MM-DD');
				if (date > latestDay) {
					return {classes: 'info'};
				}
				return {};
			},
			columns: [
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					visible: false
				},
				{
					field: 'effectiveTime',
					title: '统计日',
					halign: 'center',
					align: 'center',
					formatter: function(value, row, index) {
						var date = value;
						if (value) {
							try {
								var timeZoneID = $('#hiddenTimeZoneID').val();
								date = moment.tz(value, timeZoneID).format('YYYY-MM-DD');
							} catch (e) {}
						}
						row.effectiveDate = date;
						return date;
					}
				},
				{
					field: 'electricityPrice',
					title: '统计日电价',
					halign: 'center',
					align: 'right'
				},
				{
					field: 'electricityOfTypes',
					title: '矿场实际电量',
					halign: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						var total = 0.0;
						var tip = '';
						if (value) {
							$.each(value, function (key, value) {
								total += value;
								tip += key + ' : ' + value + "\n";
							});
						}
						var tag = '<label title="' + tip + '">' + total + '</label>';
						return tag;
					}
				},
				{
					field: 'numManagedOfTypes',
					title: '托管矿机数',
					halign: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						var total = 0;
						var tip = '';
						if (value) {
							$.each(value, function (key, value) {
								total += value;
								tip += key + ' : ' + value + "\n";
							});
						}
						var tag = '<label title="' + tip + '">' + total + '</label>';
						return tag;
					}
				},
				{
					field: 'numInvalidOfTypes',
					title: '失效矿机数',
					halign: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						var total = 0;
						var tip = '';
						if (value) {
							$.each(value, function (key, value) {
								total += value;
								tip += key + ' : ' + value + "\n";
							});
						}
						var tag = '<label title="' + tip + '">' + total + '</label>';
						return tag;
					}
				},
				{
					field: 'detectTotalCountTheory',
					title: '理论检测次数',
					halign: 'center',
					align: 'right',
					visible: false
				},
				{
					field: 'detectTotalCount',
					title: '实际检测次数',
					halign: 'center',
					align: 'right',
					visible: false
				},
				{
					field: 'effected',
					title: '是否统计',
					align: 'center',
					formatter: function(value, row, index) {
						return value == true ? '<img src="../img/icon/icon-sync-ok.png" width="20" height="20" />' : '<img src="../img/icon/icon-sync-ing.png" width="20" height="20" />';
					}
				},
				{
					field: 'effectedCount',
					title: '统计次数',
					halign: 'center',
					align: 'right'
				},
				{
					field: 'overallTheory',
					title: '状态',
					align: 'center',
					formatter: function(value, row, index) {
						return value == true ? '<i class="fa fa-lock" title="该配置已被锁定，需要具有相应权限才能执行重新统计操作。"> </i>' : '<i class="fa fa-unlock"> </i>';
					}
				},
				{
					field: 'operate',
					title: '操作',
					align: 'center',
					events: window.operateEvents = {
					        'click .detail': function (e, value, row, index) {
					        	openOptionEditDialog(row);
					        },
					        'click .restats': function (e, value, row, index) {
					        	restats(row);
					        },
					        'click .lock': function (e, value, row, index) {
					        	alert('lock');
					        },
					        'click .unlock': function (e, value, row, index) {
					        	alert('unlock');
					        }
					},
					formatter: function(value, row, index) {
						var detail = '<a class="detail" href="javascript:void(0)" title="详情"><i class="fa fa-pencil-square-o"></i></a> ';
						var restats = '<a class="restats" href="javascript:void(0)" title="重新统计"><i class="fa fa-refresh"></i></a> ';
						var lock = '<a class="lock" href="javascript:void(0)" title="锁定"><i class="fa fa-lock"></i></a> ';
						if (row.locked == true) {
							lock = '<a class="unlock" href="javascript:void(0)" title="解锁"><i class="fa fa-unlock"></i></a> ';
						}
						return [detail, restats, lock];
					}
				}
			]
		});
	}
	
	function initOptionNumMinerTable() {
		$optionNumMinerTable.bootstrapTable({
			height: 200,
			editable: true,
			columns: [
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					visible: false
				},
				{
					field: 'name',
					title: '矿机类型',
					halign: 'center',
					align: 'left'
				},
				{
					field: 'numManaged',
					title: '托管数',
					halign: 'center',
					align: 'right',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0) {
								return '无效的托管数。';
							}
							return '';
						}
					}
				},
				{
					field: 'numInvalid',
					title: '失效数',
					halign: 'center',
					align: 'right',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							var ex = /^\d+$/;
							if (!ex.test(value) || value < 0) {
								return '无效的失效数。';
							}
							return '';
						}
					}
				},
				{
					field: 'electricity',
					title: '实际电量',
					halign: 'center',
					align: 'right',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!$.isNumeric(value) || value < 0) {
								return '无效的实际电量。';
							}
							return '';
						}
					}
				}
			]
		});
	}
});